import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { catchError } from "rxjs/operators";
import { of } from "rxjs/observable/of";
import { Router } from '@angular/router';

@Injectable()
export class HttpService {

<<<<<<< HEAD
  private httpurl = 'http://192.168.1.238:8080/YYGHHospital/api/';
=======
  //private httpurl = 'http://192.168.1.238:8080/YYGHHospital/api/';
>>>>>>> a8bd0c6d08c8d5babb7ba313a8ca692406ffd5d2
  private httpurl2 = '';
 private httpurl = 'http://yuyue.cqjydata.com/YYGHHospital/api/';

  constructor(private http: HttpClient, private router: Router) { }
  //get方法
  httpGet(apiName: string, params: any): Observable<any> {
    //noinspection
    return this.http.get(this.httpurl + apiName, params).pipe(
      catchError(this.handleError('getHeroes', 'err'))
    );
  }
  //get方法
  httpGet2(apiName: string, params: any): Observable<any> {
    //noinspection
    return this.http.get(this.httpurl2 + apiName, params).pipe(
      catchError(this.handleError('getHeroes', 'err'))
    );
  }
  //post方法
  httpPost(apiName: string, params: any): Observable<any> {
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }),
    };
    return this.http.post(this.httpurl + apiName, 'data=' + params, httpOptions).pipe(
      catchError(this.handleError('getHeroes', 'err')),
    );
  }
  //数据验证
  dataFilter(res) {
    if (res == null) {
      this.router.navigate(['/404']);
    } else {
      if (res.state == 'T') {
        return true;
      } else {
        this.router.navigate(['/404']);
      }
    }
  }
  //根据身份证获取性别
  sex(id) {
    let sexnum;
    if (id.length == 18) {
      sexnum = id.substring(16, 17);
    } else {
      sexnum = id.substring(14, 15);
    }
    return sexnum % 2 == 0 ? '女' : '男';
  }
  //返回数据
  private extractData(res: Response) {
    if (res.status < 200 || res.status >= 300) {
      throw new Error('Bad response status: ' + res.status);
    }
    let body = res.json();
    //console.log(res);
    return body.data || {};
  }
  //返回失败
  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      //this.router.navigate(['/404']);
      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      console.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }
}
